<template>
  <div class="search-suggestion">
    <van-cell @click="onSearch(item)" v-for="(item,index) in list" :key="index" icon="search" >
      <template #title>
        <div v-html="highText(item)">
        </div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search.js'
import { Toast } from 'vant'
export default {
  props: {
    searchText: {
      type: String
    }
  },

  watch: {
    searchText: {
      immediate: true,
      handler () {
        clearTimeout(this.timer)
        this.timer = setTimeout(_ => {
          this.getSuggestions(this.searchText)
        }, 700)
      }
    }
  },

  data () {
    return {
      list: []
    }
  },

  created () {},

  beforeDestroy () {
    clearTimeout(this.timer)
  },

  methods: {
    async getSuggestions (q) {
      this.list = []
      try {
        const res = await getSuggestion(q)
        this.list = res.options
      } catch (err) {
        Toast.fail('出错了')
      }
    },
    highText (item) {
      const str = '<span style="color:red">' + this.searchText + '</span>'
      const reg = new RegExp(this.searchText, 'ig')
      return item.replace(reg, str)
    },
    onSearch (item) {
      this.$emit('search', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
